package com.alibaba.citrus.cr.platform.enhance.facade.service.scitem;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.platform.enhance.functions.item.ScItemEntity;
import com.alibaba.citrus.cr.platform.enhance.repository.ScItemRepository;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.bcorder.model.dto.CategoryGetCurrentCategoryByIdRequest;
import com.epoch.app.bcorder.model.dto.GetLoginEmployeeInfoResponse;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import com.epoch.app.bcorder.model.dto.ScItemExtendSDO;
import com.epoch.app.bcorder.model.dto.SearchScItemByDBWhenDegradedRequest;
import com.epoch.app.bcorder.model.dto.SearchScItemRequest;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.crplatformenhance.api.scitemquery.service.ScItemQueryService;
import com.epoch.app.crplatformenhance.dto.request.BaselineQueryScItemByPageRequest;
import com.epoch.app.crplatformenhance.dto.request.IdQueryRequest;
import com.epoch.app.crplatformenhance.dto.request.QueryScItemRequest;
import com.epoch.app.crplatformenhance.dto.response.QueryGoodsListResponse;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crplatformenhance.goodsfavorites.dto.QueryGoodsFavoritesRequest;
import com.epoch.app.crplatformenhance.goodsfavorites.model.GoodsFavorites;
import com.epoch.app.crplatformenhance.goodsfavorites.service.GoodsFavoritesService;
import com.epoch.app.crplatformenhance.model.dto.GetTopOrganizationListRequest;
import com.epoch.app.crplatformenhance.model.dto.GoodsFavoritesItem;
import com.epoch.app.crplatformenhance.model.dto.ScItemManageRangeSearchRequest;
import com.epoch.app.crplatformenhance.model.dto.ScItemSDO;
import com.epoch.app.crplatformenhance.model.dto.TopOrganizationListResponse;
import com.epoch.app.crplatformenhance.model.enums.CategoryEnum;
import com.epoch.app.crplatformenhance.model.enums.ScItemManageRangeStatus;
import com.epoch.app.crplatformenhance.scitemmanagerange.model.ScItemManageRange;
import com.epoch.app.crplatformenhance.scitemmanagerangeread.service.ScItemManageRangeReadService;
import com.epoch.app.crplatformenhance.scitemmultiple.model.ScItemMultiple;
import com.epoch.app.crplatformenhance.scitemmultipleread.dto.QueryRequest;
import com.epoch.app.crplatformenhance.scitemmultipleread.service.ScItemMultipleReadService;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * @author zls
 * @description: TODO
 * @date 2021/9/7 15:30
 */
@Primary
@Service
public class ScItemQueryServiceImpl implements ScItemQueryService {

    Log log = Log.getLogger(ScItemQueryServiceImpl.class);

    @Resource
    ScItemRepository scItemRepository;

    @Resource
    BaseDataService baseDataService;

    @Resource
    BcOrderService bcOrderService;
    @Resource
    private GoodsFavoritesService favoritesService;


    @Resource(name = "scItemsQueryTaskExecutor")
    private ThreadPoolTaskExecutor scItemsQueryTaskExecutor;

    @Resource
    private ScItemMultipleReadService scItemMultipleReadService;
    @Resource
    private ScItemManageRangeReadService scItemManageRangeReadService;
    @Resource
    private CrPlatformEnhanceService crPlatformEnhanceService;

    private static final Integer MAX_PAGE_SIZE = 1000;

    @Override
    public Result<ScItemSDO> getScItemById(IdQueryRequest request) {
        ScItemSDO scItemSDO = new ScItemSDO();
        scItemSDO.setScItemId(request.getId());
        ScItemEntity scItemEntity = ScItemEntity.of(scItemSDO);
        return Result.success(scItemEntity.doQueryById());
    }

    @Override
    public Result<List<ScItemSDO>> pageQueryScItemList(QueryScItemRequest request) {
        PageResult<List<ScItemSDO>> pageResult = scItemRepository.pageQueryScItemList(request);
        return Result.listSuccess(pageResult.getContent(), pageResult.getTotal());
    }

    @Override
    public Result<List<ScItemSDO>> pageQueryScItemListFromDB(QueryScItemRequest request) {
        PageResult<List<ScItemSDO>> pageResult = scItemRepository.pageQueryScItemListFromDB(request);
        return Result.listSuccess(pageResult.getContent(), pageResult.getTotal());
    }

    /**
     * 定制化接口，查询货品并按类目分组
     *
     * @param baselineQueryScItemByPageRequest
     * @return
     */
    @Override
    public Result<List<QueryGoodsListResponse>> queryGoodsList(BaselineQueryScItemByPageRequest baselineQueryScItemByPageRequest) {
        long start = System.currentTimeMillis();
        List outIdList = baselineQueryScItemByPageRequest.getOutIdList();
        // outerId支持模糊搜索
        String outerIdReq = "";
        if (!CollectionUtils.isEmpty(outIdList) && outIdList.size() == 1) {
            outerIdReq = outIdList.get(0).toString();
        }
        List<QueryGoodsListResponse> responseList = new ArrayList<>();

        List<com.epoch.app.bcorder.model.dto.ScItemSDO> scItemSDOListAll = Lists.newArrayList();
        List<Future<List<com.epoch.app.bcorder.model.dto.ScItemSDO>>> futureList = Lists.newArrayList();
        int totalCnt = baselineQueryScItemByPageRequest.getLimit();
        for (int i = 1; i <= totalCnt / 10; i++) {
            int finalI = i;
            String finalOuterIdReq = outerIdReq;
            CompletableFuture<List<com.epoch.app.bcorder.model.dto.ScItemSDO>> future = CompletableFuture.supplyAsync(() -> {
                Result<List<com.epoch.app.bcorder.model.dto.ScItemSDO>> searchScItemResult = null;
                // 构造查询参数
                SearchScItemByDBWhenDegradedRequest searchScItemRequest = new SearchScItemByDBWhenDegradedRequest();
                searchScItemRequest.setPageNum(baselineQueryScItemByPageRequest.getPage());
                searchScItemRequest.setPageSize(baselineQueryScItemByPageRequest.getLimit());
                try {
                    Map searchReqDTO = new HashMap();
                    if (StringUtils.isNotBlank(finalOuterIdReq)) {
                        searchReqDTO.put("outerId", finalOuterIdReq);
                    } else {
                        searchReqDTO.put("outerIdList", baselineQueryScItemByPageRequest.getOutIdList());
                    }
                    searchReqDTO.put("scItemIds", baselineQueryScItemByPageRequest.getIdList());
                    searchReqDTO.put("title", baselineQueryScItemByPageRequest.getTitle());
                    searchReqDTO.put("businessType", baselineQueryScItemByPageRequest.getBusinessType());
                    searchReqDTO.put("type", baselineQueryScItemByPageRequest.getType());
                    searchScItemRequest.setSearchReqDTO(searchReqDTO);
                    searchScItemRequest.setPageSize(10);
                    searchScItemRequest.setPageNum(finalI);
//                    log.info("分片查询参数{}", JSON.toJSONString(searchScItemRequest));
                    searchScItemResult = baseDataService.searchScItemByDBWhenDegraded(searchScItemRequest);
                } catch (Exception e) {
                    log.error("多线程查询货品异常,searchScItemRequest={}",JSON.toJSONString(searchScItemRequest), e);
                }

//                log.info("多线程查询货品结果{}", JSON.toJSONString(searchScItemResult));
                if (null == searchScItemResult) {
                    return null;
                }
                boolean success = searchScItemResult.isSuccess();
                if (!success) {
                    return null;
                }
                List<com.epoch.app.bcorder.model.dto.ScItemSDO> scItemSDOSubList = searchScItemResult.getResult();
                return scItemSDOSubList;
            }, scItemsQueryTaskExecutor);
            futureList.add(future);
        }

        for (Future<List<com.epoch.app.bcorder.model.dto.ScItemSDO>> listFuture : futureList) {
            try {
                List<com.epoch.app.bcorder.model.dto.ScItemSDO> subList = listFuture.get();
                scItemSDOListAll.addAll(Optional.ofNullable(subList).orElse(Lists.newArrayList()));
            } catch (Exception e) {
                // 异常处理
                log.error("获取多线程查询结果异常", e);

            }
        }
        log.info("queryGoodsList_goods_cost:{}",System.currentTimeMillis() - start);
        long categoryStartTime = System.currentTimeMillis();
        List<com.epoch.app.bcorder.model.dto.ScItemSDO> scItemList = Lists.newArrayList();
        Map<String, com.epoch.app.bcorder.model.dto.ScItemSDO> scItemMap = Maps.newHashMap();
        Map<String, Map> categoryMap = Maps.newHashMap();
        for (com.epoch.app.bcorder.model.dto.ScItemSDO scItemSDO : scItemSDOListAll) {
            if (scItemSDO == null || StringUtils.isBlank(scItemSDO.getOuterId())) {
                continue;
            }

            if (scItemMap.containsKey(scItemSDO.getOuterId())) {
                continue;
            }

            scItemList.add(scItemSDO);
            scItemMap.put(scItemSDO.getOuterId(), scItemSDO);

            // 获取类目
            String leafCategoryId = scItemSDO.getLeafCategoryId();
            if (StringUtils.isNotBlank(leafCategoryId) && !categoryMap.containsKey(leafCategoryId)) {
                try {
                    CategoryGetCurrentCategoryByIdRequest categoryGetCurrentCategoryByIdRequest = new CategoryGetCurrentCategoryByIdRequest();
                    categoryGetCurrentCategoryByIdRequest.setId(leafCategoryId);
                    Map tmpCategoryMap = (Map) bcOrderService.categoryGetCurrentCategoryById(categoryGetCurrentCategoryByIdRequest);
                    if (tmpCategoryMap != null && tmpCategoryMap.get("result") != null) {
                        categoryMap.put(leafCategoryId, (Map) tmpCategoryMap.get("result"));
                    }

                } catch (Exception e) {
                    log.error("获取类目信息失败", e);
                }
            }

        }
        log.info("queryGoodsList_category_cost:{}",System.currentTimeMillis() - categoryStartTime);

        // 先遍历所有货品，查询一级类目下的parentCategoryId，塞到一个sdo里面，然后根据parentCategoryId分组
        List<ScItemExtendSDO> scItemExtendSDOList = new ArrayList<>();
        for (com.epoch.app.bcorder.model.dto.ScItemSDO scItemSDO : scItemList) {
            ScItemExtendSDO scItemExtendSDO = new ScItemExtendSDO();
            BeanUtils.copyProperties(scItemSDO, scItemExtendSDO);
            String leafCategoryId = scItemSDO.getLeafCategoryId();
            if (StringUtils.isNotBlank(leafCategoryId)) {
                Map categoryResultMap = categoryMap.get(leafCategoryId);
                if (MapUtils.isNotEmpty(categoryResultMap)) {
                    String parentCategoryId = categoryResultMap.get("parentId").toString();
                    Object path = categoryResultMap.get("path");
                    List<String> pathList = JSONObject.parseArray(JSON.toJSONString(path), String.class);
                    String parentCategoryName = "";
                    if (!CollectionUtils.isEmpty(pathList) && pathList.size() < 2) {
                        parentCategoryName = pathList.get(0);
                        parentCategoryId = leafCategoryId;
                    } else if (!CollectionUtils.isEmpty(pathList) && pathList.size() == 2) {
                        parentCategoryName = pathList.get(1);
                        parentCategoryId = leafCategoryId;

                    } else if (!CollectionUtils.isEmpty(pathList) && pathList.size() > 2) {
                        parentCategoryName = pathList.get(1);
                    }
                    String currentPath = categoryResultMap.get("currentPath").toString();
                    String rootId = categoryResultMap.get("rootId").toString();
                    String parentId = categoryResultMap.get("parentId").toString();
                    String catId = categoryResultMap.get("catId").toString();
                    String idPath;
                    if (rootId.equals(parentId)) {
                        idPath = rootId + ">>" + catId;
                    } else {
                        idPath = rootId + ">>" + parentId + ">>" + catId;
                    }
                    scItemExtendSDO.setParentCategoryId(parentCategoryId);
                    scItemExtendSDO.setParentCategoryName(parentCategoryName);
                    scItemExtendSDO.setCurrentPath(currentPath);
                    scItemExtendSDO.setIdPath(idPath);
                }
            }
            scItemExtendSDOList.add(scItemExtendSDO);
        }
        // 常用货品配置
        String titleReq = baselineQueryScItemByPageRequest.getTitle();
        List<ScItemExtendSDO> scItemExtendSDORecentlyList = new ArrayList<>();
        List<String> recentlyUsedItemIdList = Lists.newArrayList();
        List<String> oriRecentlyUsedItemIdList = Optional.ofNullable(baselineQueryScItemByPageRequest.getRecentlyUsedItemIdList()).orElse(Lists.newArrayList());
        for (String s : oriRecentlyUsedItemIdList) {
            if (StringUtils.isNotBlank(s) && !recentlyUsedItemIdList.contains(s) && !"null".equalsIgnoreCase(s)) {
                recentlyUsedItemIdList.add(s);
            }
        }

        if (Objects.nonNull(recentlyUsedItemIdList)) {
            List outIdListNew = baselineQueryScItemByPageRequest.getOutIdList();
            if (!CollectionUtils.isEmpty(outIdListNew)) {
                boolean disjoint = Collections.disjoint(outIdListNew, recentlyUsedItemIdList);
                if (disjoint) {
                    recentlyUsedItemIdList = Lists.newArrayList();
                } else {
                    recentlyUsedItemIdList = outIdList;
                }
            }
            if (!CollectionUtils.isEmpty(recentlyUsedItemIdList)) {
                List<com.epoch.app.bcorder.model.dto.ScItemSDO> listResult = Lists.newArrayList();
                for (String s : recentlyUsedItemIdList) {
                    com.epoch.app.bcorder.model.dto.ScItemSDO scItem = scItemMap.get(s);
                    if (scItem != null) {
                        listResult.add(scItem);
                    }
                }

                List<ScItemExtendSDO> tmpScItemExtendSDORecentlyList = listResult.stream().map(scItemSDO -> {
                    ScItemExtendSDO scItemExtendSDO = new ScItemExtendSDO();
                    BeanUtils.copyProperties(scItemSDO, scItemExtendSDO);
                    scItemExtendSDO.setParentCategoryId(CategoryEnum.RECENTLY_USED.getCode());
                    scItemExtendSDO.setParentCategoryName("近期使用");
                    return scItemExtendSDO;
                }).collect(Collectors.toList());

                // 按照原始的添加顺序排序
                Map<String, List<ScItemExtendSDO>> recentlyUsedItemMap = Optional.ofNullable(tmpScItemExtendSDORecentlyList).orElse(Lists.newArrayList()).stream().collect(Collectors.groupingBy(ScItemExtendSDO::getOuterId));
                for (String s : recentlyUsedItemIdList) {
                    if (MapUtils.isNotEmpty(recentlyUsedItemMap) && !CollectionUtils.isEmpty(recentlyUsedItemMap.get(s))) {
                        scItemExtendSDORecentlyList.add(recentlyUsedItemMap.get(s).get(0));
                    }
                }

            }
        }
        scItemExtendSDOList.addAll(scItemExtendSDORecentlyList);

        //增加货品收藏夹类目
        List<String> goodsFavoritesList = baselineQueryScItemByPageRequest.getGoodsFavoritesList();
        //获取倍数
        Map<String, ScItemMultiple> multipleMap = getMultipleMap(scItemExtendSDOList,recentlyUsedItemIdList,
                oriRecentlyUsedItemIdList,goodsFavoritesList);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(goodsFavoritesList)){
            goodsFavoritesList=goodsFavoritesList.stream().distinct().collect(Collectors.toList());
            List<ScItemExtendSDO> scItemGoodsFavoritesList = new ArrayList<>();
            List<com.epoch.app.bcorder.model.dto.ScItemSDO> favoritesGoodsIdList = Lists.newArrayList();
            for (String s : goodsFavoritesList) {
                com.epoch.app.bcorder.model.dto.ScItemSDO scItem = scItemMap.get(s);
                if (scItem != null) {
                    favoritesGoodsIdList.add(scItem);
                }
            }
            List<ScItemExtendSDO> tmpGoodsFavoritesList = Nullable.stream(favoritesGoodsIdList).map(scItemSDO -> {
                ScItemExtendSDO scItemExtendSDO = new ScItemExtendSDO();
                BeanUtils.copyProperties(scItemSDO, scItemExtendSDO);
                scItemExtendSDO.setParentCategoryId(CategoryEnum.FAVORITES.getCode());
                scItemExtendSDO.setParentCategoryName("收藏夹");
                return scItemExtendSDO;
            }).collect(Collectors.toList());


            Map<String, List<ScItemExtendSDO>> favoritesItemMap = Optional.ofNullable(tmpGoodsFavoritesList).orElse(Lists.newArrayList()).stream().collect(Collectors.groupingBy(ScItemExtendSDO::getOuterId));
            for (String s : goodsFavoritesList) {
                if (MapUtils.isNotEmpty(favoritesItemMap) && !CollectionUtils.isEmpty(favoritesItemMap.get(s))) {
                    scItemGoodsFavoritesList.add(favoritesItemMap.get(s).get(0));
                }
            }
            scItemExtendSDOList.addAll(scItemGoodsFavoritesList);
        }


        //根据父级类目id分组，支持类目为空
        Map<Optional<String>, List<ScItemExtendSDO>> collectMap = scItemExtendSDOList.stream().collect(Collectors.groupingBy(x -> Optional.ofNullable(x.getParentCategoryId())));
        // 遍历分组
        for (Optional<String> key : collectMap.keySet()) {
            QueryGoodsListResponse queryGoodsListResponse = new QueryGoodsListResponse();
            // 没有类目的默认类目id为0，名称叫”未分类的“
            if (!key.isPresent()) {
                continue;
//                queryGoodsListResponse.setValue("0");
//                queryGoodsListResponse.setLabel("未分类的");
            } else {
                List<ScItemExtendSDO> scItemExtendSDOList1 = collectMap.get(key);
                if (CollectionUtils.isEmpty(scItemExtendSDOList1)) {
                    continue;
                }
                queryGoodsListResponse.setValue(key.get());
                ScItemExtendSDO scItemExtendSDO = collectMap.get(key).get(0);
                queryGoodsListResponse.setLabel(scItemExtendSDO.getParentCategoryName());
            }
            List<Map> resultMapList = new ArrayList<>();
            // 遍历每组的列表
            List<ScItemExtendSDO> scItemExtendSDOListNew = collectMap.get(key);
            if (CollectionUtils.isEmpty(scItemExtendSDOListNew)) {
                continue;
            }
            for (ScItemExtendSDO scItemSDO : scItemExtendSDOListNew) {
                String currentPath = scItemSDO.getCurrentPath();
                String idPath = scItemSDO.getIdPath();
                Map scItemSDOMap = new HashMap();
                String title = scItemSDO.getTitle();
                String scItemId = scItemSDO.getScItemId();
                String outerId = scItemSDO.getOuterId();
                String unit = scItemSDO.getUnit();
                Map<String, String> features = scItemSDO.getFeatures();
                /*
                 背景:创建预报订单或者销售订单添加货品时，页面需要渲染货品的单位名称
                 现有的逻辑，单位名称取自unit字段
                 由于unit字段可能为空，因此多加一个字段unitNameDesc，若unit字段为空，可以取unitNameDesc
                 */
                String unitNameDesc = features.get("unitNameDesc");
                scItemSDOMap.put("goodsCode", outerId);
                scItemSDOMap.put("id", scItemId);
                scItemSDOMap.put("goodsName", title);
                scItemSDOMap.put("baseUnitCode", features.get("unitName"));
                scItemSDOMap.put("baseUnitName", StringUtils.isBlank(unit) ? unitNameDesc : unit);
                // 类目名称路径
                if (StringUtils.isNotBlank(currentPath)) {
                    scItemSDOMap.put("currentPath", currentPath);
                }
                // 类目ID路径
                if (StringUtils.isNotBlank(idPath)) {
                    scItemSDOMap.put("idPath", idPath);
                }
                // 品类划分编码
                String category = features.get("category");
                if (StringUtils.isNotBlank(category)) {
                    scItemSDOMap.put("category", category);
                }
                // 品类划分描述
                String categoryDesc = features.get("categoryDesc");
                if (StringUtils.isNotBlank(categoryDesc)) {
                    scItemSDOMap.put("categoryDesc", categoryDesc);
                }
                // 品项编码
                String categoryChildCode = features.get("categoryChildCode");
                if (StringUtils.isNotBlank(categoryChildCode)) {
                    scItemSDOMap.put("categoryChildCode", categoryChildCode);
                }
                // 品项编码描述
                String categoryChildDesc = features.get("categoryChildDesc");
                if (StringUtils.isNotBlank(categoryChildDesc)) {
                    scItemSDOMap.put("categoryChildDesc", categoryChildDesc);
                }
                String guaranteePeriod = features.get("guaranteePeriod");
                if (StringUtils.isNotBlank(guaranteePeriod)) {
                    scItemSDOMap.put("guaranteePeriod", guaranteePeriod);
                }
                //放入倍数
                if (multipleMap.get(outerId) != null){
                    scItemSDOMap.put("scItemMultiple",multipleMap.get(outerId).getMultiple());
                }
                resultMapList.add(scItemSDOMap);
            }
            queryGoodsListResponse.setGoodsList(resultMapList);
            responseList.add(queryGoodsListResponse);
        }
        // 将近期使用分组放到第二个
        List<QueryGoodsListResponse> collectRecent = responseList.stream()
                .filter(queryGoodsListResponse -> CategoryEnum.RECENTLY_USED.getCode().equals(queryGoodsListResponse.getValue())).collect(Collectors.toList());

        // 将收藏夹分组放到第一个
        List<QueryGoodsListResponse> collectFavorites = responseList.stream()
                .filter(queryGoodsListResponse -> CategoryEnum.FAVORITES.getCode().equals(queryGoodsListResponse.getValue())).collect(Collectors.toList());


        List<QueryGoodsListResponse> collect = responseList.stream()
                .filter(queryGoodsListResponse -> !CategoryEnum.RECENTLY_USED.getCode().equals(queryGoodsListResponse.getValue()) && !CategoryEnum.FAVORITES.getCode().equals(queryGoodsListResponse.getValue()))
                .sorted(Comparator.comparing(QueryGoodsListResponse::getValue)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collectRecent)) {
            collect.add(0, collectRecent.get(0));
        }else {
            collect.add(0, new QueryGoodsListResponse(){{
                setLabel("近期使用");
                setValue(CategoryEnum.RECENTLY_USED.getCode());
                setGoodsList(Lists.newArrayList());
            }});
        }

        if (!CollectionUtils.isEmpty(collectFavorites)) {
            collect.add(0, collectFavorites.get(0));
        }else {
            collect.add(0, new QueryGoodsListResponse(){{
                setLabel("收藏夹");
                setValue(CategoryEnum.FAVORITES.getCode());
                setGoodsList(Lists.newArrayList());
            }});
        }
        log.info("queryGoodsList_all_cost:{}",System.currentTimeMillis() - start);
        return Result.listSuccess(collect, collect.size());
    }


    @Override
    public Result<List<QueryGoodsListResponse>> queryGoodsListForForecastSale(BaselineQueryScItemByPageRequest baselineQueryScItemByPageRequest) {
        long start = System.currentTimeMillis();
        List outIdList = baselineQueryScItemByPageRequest.getOutIdList();
        // outerId支持模糊搜索
        String outerIdReq = "";
        if (!CollectionUtils.isEmpty(outIdList) && outIdList.size() == 1) {
            outerIdReq = outIdList.get(0).toString();
        }
        List<QueryGoodsListResponse> responseList = new ArrayList<>();
        //GetLoginEmployeeInfoResponse loginEmployeeInfo = baseDataService.getLoginEmployeeInfo();
        List<com.epoch.app.bcorder.model.dto.ScItemSDO> scItemSDOListAll = Lists.newArrayList();
        List<Future<List<com.epoch.app.bcorder.model.dto.ScItemSDO>>> futureList = Lists.newArrayList();
        int totalCnt = baselineQueryScItemByPageRequest.getLimit();
        for (int i = 1; i <= totalCnt / 10; i++) {
            int finalI = i;
            String finalOuterIdReq = outerIdReq;
            CompletableFuture<List<com.epoch.app.bcorder.model.dto.ScItemSDO>> future = CompletableFuture.supplyAsync(() -> {
                Result<List<com.epoch.app.bcorder.model.dto.ScItemSDO>> searchScItemResult = null;
                // 构造查询参数
                SearchScItemByDBWhenDegradedRequest searchScItemRequest = new SearchScItemByDBWhenDegradedRequest();
                searchScItemRequest.setPageNum(baselineQueryScItemByPageRequest.getPage());
                searchScItemRequest.setPageSize(baselineQueryScItemByPageRequest.getLimit());
                try {
                    Map searchReqDTO = new HashMap();
                    if (StringUtils.isNotBlank(finalOuterIdReq)) {
                        searchReqDTO.put("outerId", finalOuterIdReq);
                    } else {
                        searchReqDTO.put("outerIdList", baselineQueryScItemByPageRequest.getOutIdList());
                    }
                    searchReqDTO.put("scItemIds", baselineQueryScItemByPageRequest.getIdList());
                    searchReqDTO.put("title", baselineQueryScItemByPageRequest.getTitle());
                    searchReqDTO.put("businessType", baselineQueryScItemByPageRequest.getBusinessType());
                    searchReqDTO.put("type", baselineQueryScItemByPageRequest.getType());
                    searchScItemRequest.setSearchReqDTO(searchReqDTO);
                    searchScItemRequest.setPageSize(10);
                    searchScItemRequest.setPageNum(finalI);
//                    log.info("分片查询参数{}", JSON.toJSONString(searchScItemRequest));
                    searchScItemResult = baseDataService.searchScItemByDBWhenDegraded(searchScItemRequest);
                } catch (Exception e) {
                    log.error("多线程查询货品异常,searchScItemRequest={}",JSON.toJSONString(searchScItemRequest), e);
                }

//                log.info("多线程查询货品结果{}", JSON.toJSONString(searchScItemResult));
                if (null == searchScItemResult) {
                    return null;
                }
                boolean success = searchScItemResult.isSuccess();
                if (!success) {
                    return null;
                }
                List<com.epoch.app.bcorder.model.dto.ScItemSDO> scItemSDOSubList = searchScItemResult.getResult();
                return scItemSDOSubList;
            }, scItemsQueryTaskExecutor);
            futureList.add(future);
        }

        for (Future<List<com.epoch.app.bcorder.model.dto.ScItemSDO>> listFuture : futureList) {
            try {
                List<com.epoch.app.bcorder.model.dto.ScItemSDO> subList = listFuture.get();
                scItemSDOListAll.addAll(Optional.ofNullable(subList).orElse(Lists.newArrayList()));
            } catch (Exception e) {
                // 异常处理
                log.error("获取多线程查询结果异常", e);

            }
        }
        log.info("queryGoodsList_goods_cost:{}",System.currentTimeMillis() - start);
        long categoryStartTime = System.currentTimeMillis();
        List<com.epoch.app.bcorder.model.dto.ScItemSDO> scItemList = Lists.newArrayList();
        Map<String, com.epoch.app.bcorder.model.dto.ScItemSDO> scItemMap = Maps.newHashMap();
        Map<String, Map> categoryMap = Maps.newHashMap();

        //过滤掉货品经营范围
        List<ScItemManageRange> scItemManageRanges = searchScItemManageRanges();
        log.info("search_scItem_manage_ranges_result:{}",JSON.toJSONString(scItemManageRanges));
        //如果经营范围不是空的
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(scItemManageRanges)){
            //如果有多个销售组织 先看看是不是全部都禁用 如果是 那就直接通过; 否则再剔除掉全部禁用的组织;
            boolean allDisabled = scItemManageRanges.stream().allMatch(x -> ScItemManageRangeStatus.DISABLED.getValue().equals(x.getStatus()));
            if (!allDisabled){
                Map<String, List<ScItemManageRange>> saleOrgId2RangeMap = scItemManageRanges.stream().collect(Collectors.groupingBy(ScItemManageRange::getSaleOrgId));
                //如果有多个销售组织
                if (saleOrgId2RangeMap.size() > 1){
                    //移除掉某个组织全部禁用的
                    saleOrgId2RangeMap.values().forEach(ranges->{
                        boolean disabled = ranges.stream().allMatch(x -> ScItemManageRangeStatus.DISABLED.getValue().equals(x.getStatus()));
                        if (disabled){
                            scItemManageRanges.removeAll(ranges);
                        }
                    });
                }
                scItemSDOListAll = scItemSDOListAll.stream().filter(scItemSDO ->
                        scItemManageRanges.stream().anyMatch(scItemManageRange ->
                                Objects.equals(scItemManageRange.getScItemId(),scItemSDO.getScItemId()) &&
                                        ScItemManageRangeStatus.ENABLE.getValue().equals(scItemManageRange.getStatus()))).collect(Collectors.toList());

            }
        }
        for (com.epoch.app.bcorder.model.dto.ScItemSDO scItemSDO : scItemSDOListAll) {
            if (scItemSDO == null || StringUtils.isBlank(scItemSDO.getOuterId())) {
                continue;
            }

            if (scItemMap.containsKey(scItemSDO.getOuterId())) {
                continue;
            }

            scItemList.add(scItemSDO);
            scItemMap.put(scItemSDO.getOuterId(), scItemSDO);

            // 获取类目
            String leafCategoryId = scItemSDO.getLeafCategoryId();
            if (StringUtils.isNotBlank(leafCategoryId) && !categoryMap.containsKey(leafCategoryId)) {
                try {
                    CategoryGetCurrentCategoryByIdRequest categoryGetCurrentCategoryByIdRequest = new CategoryGetCurrentCategoryByIdRequest();
                    categoryGetCurrentCategoryByIdRequest.setId(leafCategoryId);
                    Map tmpCategoryMap = (Map) bcOrderService.categoryGetCurrentCategoryById(categoryGetCurrentCategoryByIdRequest);
                    if (tmpCategoryMap != null && tmpCategoryMap.get("result") != null) {
                        categoryMap.put(leafCategoryId, (Map) tmpCategoryMap.get("result"));
                    }

                } catch (Exception e) {
                    log.error("获取类目信息失败", e);
                }
            }

        }
        log.info("queryGoodsList_category_cost:{}",System.currentTimeMillis() - categoryStartTime);

        // 先遍历所有货品，查询一级类目下的parentCategoryId，塞到一个sdo里面，然后根据parentCategoryId分组
        List<ScItemExtendSDO> scItemExtendSDOList = new ArrayList<>();
        for (com.epoch.app.bcorder.model.dto.ScItemSDO scItemSDO : scItemList) {
            ScItemExtendSDO scItemExtendSDO = new ScItemExtendSDO();
            BeanUtils.copyProperties(scItemSDO, scItemExtendSDO);
            String leafCategoryId = scItemSDO.getLeafCategoryId();
            if (StringUtils.isNotBlank(leafCategoryId)) {
                Map categoryResultMap = categoryMap.get(leafCategoryId);
                if (MapUtils.isNotEmpty(categoryResultMap)) {
                    String parentCategoryId = categoryResultMap.get("parentId").toString();
                    Object path = categoryResultMap.get("path");
                    List<String> pathList = JSONObject.parseArray(JSON.toJSONString(path), String.class);
                    String parentCategoryName = "";
                    if (!CollectionUtils.isEmpty(pathList) && pathList.size() < 2) {
                        parentCategoryName = pathList.get(0);
                        parentCategoryId = leafCategoryId;
                    } else if (!CollectionUtils.isEmpty(pathList) && pathList.size() == 2) {
                        parentCategoryName = pathList.get(1);
                        parentCategoryId = leafCategoryId;

                    } else if (!CollectionUtils.isEmpty(pathList) && pathList.size() > 2) {
                        parentCategoryName = pathList.get(1);
                    }
                    String currentPath = categoryResultMap.get("currentPath").toString();
                    String rootId = categoryResultMap.get("rootId").toString();
                    String parentId = categoryResultMap.get("parentId").toString();
                    String catId = categoryResultMap.get("catId").toString();
                    String idPath;
                    if (rootId.equals(parentId)) {
                        idPath = rootId + ">>" + catId;
                    } else {
                        idPath = rootId + ">>" + parentId + ">>" + catId;
                    }
                    scItemExtendSDO.setParentCategoryId(parentCategoryId);
                    scItemExtendSDO.setParentCategoryName(parentCategoryName);
                    scItemExtendSDO.setCurrentPath(currentPath);
                    scItemExtendSDO.setIdPath(idPath);
                }
            }
            scItemExtendSDOList.add(scItemExtendSDO);
        }
        // 常用货品配置
        String titleReq = baselineQueryScItemByPageRequest.getTitle();
        List<ScItemExtendSDO> scItemExtendSDORecentlyList = new ArrayList<>();
        List<String> recentlyUsedItemIdList = Lists.newArrayList();
        List<String> oriRecentlyUsedItemIdList = Optional.ofNullable(baselineQueryScItemByPageRequest.getRecentlyUsedItemIdList()).orElse(Lists.newArrayList());
        for (String s : oriRecentlyUsedItemIdList) {
            if (StringUtils.isNotBlank(s) && !recentlyUsedItemIdList.contains(s) && !"null".equalsIgnoreCase(s)) {
                recentlyUsedItemIdList.add(s);
            }
        }

        if (Objects.nonNull(recentlyUsedItemIdList)) {
            List outIdListNew = baselineQueryScItemByPageRequest.getOutIdList();
            if (!CollectionUtils.isEmpty(outIdListNew)) {
                boolean disjoint = Collections.disjoint(outIdListNew, recentlyUsedItemIdList);
                if (disjoint) {
                    recentlyUsedItemIdList = Lists.newArrayList();
                } else {
                    recentlyUsedItemIdList = outIdList;
                }
            }
            if (!CollectionUtils.isEmpty(recentlyUsedItemIdList)) {
                List<com.epoch.app.bcorder.model.dto.ScItemSDO> listResult = Lists.newArrayList();
                for (String s : recentlyUsedItemIdList) {
                    com.epoch.app.bcorder.model.dto.ScItemSDO scItem = scItemMap.get(s);
                    if (scItem != null) {
                        listResult.add(scItem);
                    }
                }

                List<ScItemExtendSDO> tmpScItemExtendSDORecentlyList = listResult.stream().map(scItemSDO -> {
                    ScItemExtendSDO scItemExtendSDO = new ScItemExtendSDO();
                    BeanUtils.copyProperties(scItemSDO, scItemExtendSDO);
                    scItemExtendSDO.setParentCategoryId(CategoryEnum.RECENTLY_USED.getCode());
                    scItemExtendSDO.setParentCategoryName("近期使用");
                    return scItemExtendSDO;
                }).collect(Collectors.toList());

                // 按照原始的添加顺序排序
                Map<String, List<ScItemExtendSDO>> recentlyUsedItemMap = Optional.ofNullable(tmpScItemExtendSDORecentlyList).orElse(Lists.newArrayList()).stream().collect(Collectors.groupingBy(ScItemExtendSDO::getOuterId));
                for (String s : recentlyUsedItemIdList) {
                    if (MapUtils.isNotEmpty(recentlyUsedItemMap) && !CollectionUtils.isEmpty(recentlyUsedItemMap.get(s))) {
                        scItemExtendSDORecentlyList.add(recentlyUsedItemMap.get(s).get(0));
                    }
                }

            }
        }
        scItemExtendSDOList.addAll(scItemExtendSDORecentlyList);

        //增加货品收藏夹类目
        List<String> goodsFavoritesList = baselineQueryScItemByPageRequest.getGoodsFavoritesList();
        //获取倍数
        Map<String, ScItemMultiple> multipleMap = getMultipleMap(scItemExtendSDOList,recentlyUsedItemIdList,
                oriRecentlyUsedItemIdList,goodsFavoritesList);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(goodsFavoritesList)){
            goodsFavoritesList=goodsFavoritesList.stream().distinct().collect(Collectors.toList());
            List<ScItemExtendSDO> scItemGoodsFavoritesList = new ArrayList<>();
            List<com.epoch.app.bcorder.model.dto.ScItemSDO> favoritesGoodsIdList = Lists.newArrayList();
            for (String s : goodsFavoritesList) {
                com.epoch.app.bcorder.model.dto.ScItemSDO scItem = scItemMap.get(s);
                if (scItem != null) {
                    favoritesGoodsIdList.add(scItem);
                }
            }
            List<ScItemExtendSDO> tmpGoodsFavoritesList = Nullable.stream(favoritesGoodsIdList).map(scItemSDO -> {
                ScItemExtendSDO scItemExtendSDO = new ScItemExtendSDO();
                BeanUtils.copyProperties(scItemSDO, scItemExtendSDO);
                scItemExtendSDO.setParentCategoryId(CategoryEnum.FAVORITES.getCode());
                scItemExtendSDO.setParentCategoryName("收藏夹");
                return scItemExtendSDO;
            }).collect(Collectors.toList());


            Map<String, List<ScItemExtendSDO>> favoritesItemMap = Optional.ofNullable(tmpGoodsFavoritesList).orElse(Lists.newArrayList()).stream().collect(Collectors.groupingBy(ScItemExtendSDO::getOuterId));
            for (String s : goodsFavoritesList) {
                if (MapUtils.isNotEmpty(favoritesItemMap) && !CollectionUtils.isEmpty(favoritesItemMap.get(s))) {
                    scItemGoodsFavoritesList.add(favoritesItemMap.get(s).get(0));
                }
            }
            scItemExtendSDOList.addAll(scItemGoodsFavoritesList);
        }


        //根据父级类目id分组，支持类目为空
        Map<Optional<String>, List<ScItemExtendSDO>> collectMap = scItemExtendSDOList.stream().collect(Collectors.groupingBy(x -> Optional.ofNullable(x.getParentCategoryId())));
        // 遍历分组
        for (Optional<String> key : collectMap.keySet()) {
            QueryGoodsListResponse queryGoodsListResponse = new QueryGoodsListResponse();
            // 没有类目的默认类目id为0，名称叫”未分类的“
            if (!key.isPresent()) {
                continue;
//                queryGoodsListResponse.setValue("0");
//                queryGoodsListResponse.setLabel("未分类的");
            } else {
                List<ScItemExtendSDO> scItemExtendSDOList1 = collectMap.get(key);
                if (CollectionUtils.isEmpty(scItemExtendSDOList1)) {
                    continue;
                }
                queryGoodsListResponse.setValue(key.get());
                ScItemExtendSDO scItemExtendSDO = collectMap.get(key).get(0);
                queryGoodsListResponse.setLabel(scItemExtendSDO.getParentCategoryName());
            }
            List<Map> resultMapList = new ArrayList<>();
            // 遍历每组的列表
            List<ScItemExtendSDO> scItemExtendSDOListNew = collectMap.get(key);
            if (CollectionUtils.isEmpty(scItemExtendSDOListNew)) {
                continue;
            }
            for (ScItemExtendSDO scItemSDO : scItemExtendSDOListNew) {
                String currentPath = scItemSDO.getCurrentPath();
                String idPath = scItemSDO.getIdPath();
                Map scItemSDOMap = new HashMap();
                String title = scItemSDO.getTitle();
                String scItemId = scItemSDO.getScItemId();
                String outerId = scItemSDO.getOuterId();
                String barCode = scItemSDO.getBarCode();
                String unit = scItemSDO.getUnit();
                Map<String, String> features = scItemSDO.getFeatures();
                /*
                 背景:创建预报订单或者销售订单添加货品时，页面需要渲染货品的单位名称
                 现有的逻辑，单位名称取自unit字段
                 由于unit字段可能为空，因此多加一个字段unitNameDesc，若unit字段为空，可以取unitNameDesc
                 */
                String unitNameDesc = features.get("unitNameDesc");
                scItemSDOMap.put("goodsCode", outerId);
                scItemSDOMap.put("barCode", barCode);
                scItemSDOMap.put("id", scItemId);
                scItemSDOMap.put("goodsName", title);
                scItemSDOMap.put("baseUnitCode", features.get("unitName"));
                scItemSDOMap.put("baseUnitName", StringUtils.isBlank(unit) ? unitNameDesc : unit);
                // 类目名称路径
                if (StringUtils.isNotBlank(currentPath)) {
                    scItemSDOMap.put("currentPath", currentPath);
                }
                // 类目ID路径
                if (StringUtils.isNotBlank(idPath)) {
                    scItemSDOMap.put("idPath", idPath);
                }
                // 品类划分编码
                String category = features.get("category");
                if (StringUtils.isNotBlank(category)) {
                    scItemSDOMap.put("category", category);
                }
                // 品类划分描述
                String categoryDesc = features.get("categoryDesc");
                if (StringUtils.isNotBlank(categoryDesc)) {
                    scItemSDOMap.put("categoryDesc", categoryDesc);
                }
                // 品项编码
                String categoryChildCode = features.get("categoryChildCode");
                if (StringUtils.isNotBlank(categoryChildCode)) {
                    scItemSDOMap.put("categoryChildCode", categoryChildCode);
                }
                // 品项编码描述
                String categoryChildDesc = features.get("categoryChildDesc");
                if (StringUtils.isNotBlank(categoryChildDesc)) {
                    scItemSDOMap.put("categoryChildDesc", categoryChildDesc);
                }
                String guaranteePeriod = features.get("guaranteePeriod");
                if (StringUtils.isNotBlank(guaranteePeriod)) {
                    scItemSDOMap.put("guaranteePeriod", guaranteePeriod);
                }
                //放入倍数
                if (multipleMap.get(outerId) != null){
                    scItemSDOMap.put("scItemMultiple",multipleMap.get(outerId).getMultiple());
                }
                resultMapList.add(scItemSDOMap);
            }
            queryGoodsListResponse.setGoodsList(resultMapList);
            responseList.add(queryGoodsListResponse);
        }
        // 将近期使用分组放到第二个
        List<QueryGoodsListResponse> collectRecent = responseList.stream()
                .filter(queryGoodsListResponse -> CategoryEnum.RECENTLY_USED.getCode().equals(queryGoodsListResponse.getValue())).collect(Collectors.toList());

        // 将收藏夹分组放到第一个
        List<QueryGoodsListResponse> collectFavorites = responseList.stream()
                .filter(queryGoodsListResponse -> CategoryEnum.FAVORITES.getCode().equals(queryGoodsListResponse.getValue())).collect(Collectors.toList());


        List<QueryGoodsListResponse> collect = responseList.stream()
                .filter(queryGoodsListResponse -> !CategoryEnum.RECENTLY_USED.getCode().equals(queryGoodsListResponse.getValue()) && !CategoryEnum.FAVORITES.getCode().equals(queryGoodsListResponse.getValue()))
                .sorted(Comparator.comparing(QueryGoodsListResponse::getValue)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collectRecent)) {
            collect.add(0, collectRecent.get(0));
        }else {
            collect.add(0, new QueryGoodsListResponse(){{
                setLabel("近期使用");
                setValue(CategoryEnum.RECENTLY_USED.getCode());
                setGoodsList(Lists.newArrayList());
            }});
        }

        if (!CollectionUtils.isEmpty(collectFavorites)) {
            collect.add(0, collectFavorites.get(0));
        }else {
            collect.add(0, new QueryGoodsListResponse(){{
                setLabel("收藏夹");
                setValue(CategoryEnum.FAVORITES.getCode());
                setGoodsList(Lists.newArrayList());
            }});
        }
        log.info("queryGoodsList_all_cost:{}",System.currentTimeMillis() - start);
        return Result.listSuccess(collect, collect.size());
    }

    /**
     *  用于门店库存查询货品明细,会使用分子公司经营货品范围进行过滤
     */
    @Override
    @FacadeInvoker
    public Result<List<QueryGoodsListResponse>> queryGoodsListForStoreInventory(BaselineQueryScItemByPageRequest baselineQueryScItemByPageRequest) {
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(baselineQueryScItemByPageRequest.getOutIdList())
        && baselineQueryScItemByPageRequest.getOutIdList().stream().filter(Objects::nonNull).anyMatch(o -> o.toString().length() > 20)){
            throw new FacadeException("OTS-03-005-00-15-445",20);
        }
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(baselineQueryScItemByPageRequest.getGoodsFavoritesList())) {
            Result<List<GoodsFavorites>> goodsFavoritesResult = favoritesService.queryGoodsFavorites(
                    new QueryGoodsFavoritesRequest());
            log.info("查询货品收藏夹出参:" + JSONObject.toJSONString(goodsFavoritesResult));
            if (Objects.nonNull(goodsFavoritesResult) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(goodsFavoritesResult.getResult())) {
                GoodsFavorites goodsFavorites = goodsFavoritesResult.getResult().get(0);
                String goodsList = goodsFavorites.getGoodsList();
                if (org.apache.commons.lang3.StringUtils.isNotBlank(goodsList) && !"[]".equalsIgnoreCase(goodsList)) {
                    List<GoodsFavoritesItem> goodsFavoritesItems = JSONObject.parseArray(goodsList,
                            GoodsFavoritesItem.class);
                    List<String> goodsCodes = goodsFavoritesItems.stream().map(GoodsFavoritesItem::getGoodsCode)
                            .collect(Collectors.toList());
                    baselineQueryScItemByPageRequest.setGoodsFavoritesList(goodsCodes);
                }
            }
        }
        return queryGoodsListForForecastSale(baselineQueryScItemByPageRequest);
    }

    private Map<String, ScItemMultiple> getMultipleMap(List<ScItemExtendSDO> scItemExtendSDOS,
                                                       List<String> recentlyUsedScItemCodes,
                                                       List<String> originRecentlyUsedScItemCodes,
                                                       List<String> goodsFavoritesList){
        Map<String,ScItemMultiple> map = Maps.newHashMap();
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(scItemExtendSDOS)){
            return map;
        }
        List<String> scItemCodes = scItemExtendSDOS.stream().filter(Objects::nonNull).map(ScItemExtendSDO::getOuterId)
                .filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
        List<String> allScItemCodes = Lists.newArrayList();
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(scItemCodes)){
            allScItemCodes.addAll(scItemCodes);
        }
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(recentlyUsedScItemCodes)){
            allScItemCodes.addAll(recentlyUsedScItemCodes);
        }
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(originRecentlyUsedScItemCodes)){
            allScItemCodes.addAll(originRecentlyUsedScItemCodes);
        }
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(goodsFavoritesList)){
            allScItemCodes.addAll(goodsFavoritesList);
        }
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(allScItemCodes)){
            return map;
        }
        allScItemCodes = allScItemCodes.stream().distinct().collect(Collectors.toList());
        QueryRequest queryRequest = new QueryRequest();
        queryRequest.setScItemCodeList(allScItemCodes);
        queryRequest.setLimit(MAX_PAGE_SIZE);
//        queryRequest.setLimit(allScItemCodes.size());
        Result<List<ScItemMultiple>> query = scItemMultipleReadService.query(queryRequest);
        log.info("ScItemQueryServiceImpl_query_result:{}",JSON.toJSONString(query));
        if (query == null || org.apache.commons.collections4.CollectionUtils.isEmpty(query.getResult())){
            return map;
        }
        int total = query.getTotal();
        if (total < MAX_PAGE_SIZE){
            return query.getResult().stream().collect(Collectors.toMap(ScItemMultiple::getScItemCode,x->x,(a,b)->a));
        }else {
            int page = total % MAX_PAGE_SIZE == 0? total / MAX_PAGE_SIZE :
                    total / MAX_PAGE_SIZE + 1;
            List<ScItemMultiple> scItemMultiples = Lists.newArrayList();
            for (int i =0; i < page ;i++){
                QueryRequest request = new QueryRequest();
                request.setScItemCodeList(allScItemCodes);
                request.setStart(i * MAX_PAGE_SIZE);
                request.setLimit(MAX_PAGE_SIZE);
                Result<List<ScItemMultiple>> result = scItemMultipleReadService.query(request);
                if (result != null && org.apache.commons.collections4.CollectionUtils.isNotEmpty(result.getResult())){
                    scItemMultiples.addAll(result.getResult());
                }
            }
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(scItemMultiples)){
                return scItemMultiples.stream().collect(Collectors.toMap(ScItemMultiple::getScItemCode,x->x,(a,b)->a));
            }
        }
        return map;
    }

    private List<ScItemManageRange> searchScItemManageRanges(){
        Result<List<ScItemManageRange>> search = scItemManageRangeReadService.searchWithPermission();
        if (search != null && org.apache.commons.collections4.CollectionUtils.isNotEmpty(search.getResult())){
            return search.getResult();
        }
        return null;
    }

    public static void main(String[] args) {
        List<String> list1 = null;
        List<String> list2 = Lists.newArrayList("1111");
        boolean disjoint1 = Collections.disjoint(list1, list2);
        boolean disjoint2 = Collections.disjoint(list2, list1);
        System.out.println(disjoint1);
        System.out.println(disjoint2);
    }
}
